package com.yujistu.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dd.CircularProgressButton;
import com.yujistu.R;
import com.yujistu.framework.http.ResultListener;
import com.yujistu.integration.request.FindPWDRequest;
import com.yujistu.integration.request.ForgetPWDCodeRequest;
import com.yujistu.integration.request.ForgetPWDResult;
import com.yujistu.integration.request.RegistrationRequest;
import com.yujistu.integration.request.SendREGCodeRequest;
import com.yujistu.integration.result.FindPWDResult;
import com.yujistu.integration.result.RegisterResult;
import com.yujistu.utils.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by S3YOGA on 2015/11/3.
 */
public class RegisterActivity extends BaseActivity {

    public static final String INTENT_FLAG_IS_FORGET_PASSWORD = "forget_password";

    EditText  phoneET;
    EditText  codeET;
    EditText  pwdET;
    Button    getSMS;
    ImageView  rightIV;
    TextView  pwdTV;
    TextView  linkTV;
    CircularProgressButton  registerCPB;
    TimeCountUtil  timeCountUtil;
    boolean isForgetPWD = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        isForgetPWD = getIntent().getBooleanExtra(INTENT_FLAG_IS_FORGET_PASSWORD, false);
        initView();
    }

    private void initView() {
        TextView title = (TextView)findViewById(R.id.tv_title_title);
        pwdTV = (TextView)findViewById(R.id.pwdTV);

        rightIV = (ImageView)findViewById(R.id.title_right_iv);
        rightIV.setBackgroundResource(R.mipmap.cancel);
        rightIV.setVisibility(View.VISIBLE);
        rightIV.setOnClickListener(mOnClickListener);

        phoneET = (EditText)findViewById(R.id.register_mobileET);
        codeET = (EditText)findViewById(R.id.code_mobileET);
        pwdET = (EditText)findViewById(R.id.pwdET);
        getSMS = (Button)findViewById(R.id.register_smsBTN);
        getSMS.setOnClickListener(mOnClickListener);
        linkTV = (TextView)findViewById(R.id.protocol_link_tv);
        linkTV.setOnClickListener(mOnClickListener);

        findViewById(R.id.registerCPB).setOnClickListener(mOnClickListener);
        registerCPB = (CircularProgressButton)findViewById(R.id.registerCPB);
        registerCPB.setIndeterminateProgressMode(true);
        registerCPB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(registerCPB.getProgress() == 0){
                    checkInfoAndLogin();
                }else if(registerCPB.getProgress() == 100){
                    registerCPB.setProgress(0);
                }else{
                    registerCPB.setProgress(100);
                }
            }
        });

        View registerProtocolLL = findViewById(R.id.register_protocol_ll);
        if(isForgetPWD){
            registerCPB.setText(R.string.submit);
            registerProtocolLL.setVisibility(View.INVISIBLE);
            title.setText(R.string.find_pwd);
            pwdTV.setText(R.string.new_pwd_more_than_six);
            linkTV.setVisibility(View.GONE);
        } else{
            registerProtocolLL.setVisibility(View.VISIBLE);
            title.setText(R.string.register);
            linkTV.setVisibility(View.VISIBLE);
        }
    }

    private void checkInfoAndLogin() {
        if(isUserNameValid(phoneET.getText().toString()) && isCodeValid(codeET.getText().toString()) && isPasswordValid(pwdET.getText().toString())){
            registerCPB.setProgress(50);
            if(!isForgetPWD){
                doRegister();
            }else{
                doForgetPWD();
            }
        }
    }

    private boolean isUserNameValid(String userName) {
        boolean result = TextUtils.isEmpty(userName);
        if(result){
            Animation shake = AnimationUtils.loadAnimation(this,R.anim.edittext_shake);
            phoneET.startAnimation(shake);
            return false;
        }
        return true;
    }

    private boolean isCodeValid(String code) {
        boolean  result = TextUtils.isEmpty(code);
        if(result || code.length() < 6){
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.edittext_shake);
            codeET.startAnimation(shake);
            return false;
        }
        return  true;
    }

    private boolean isPasswordValid(String password) {
        boolean result = TextUtils.isEmpty(password);
        if(result || password.length() < 6){
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.edittext_shake);
            pwdET.startAnimation(shake);
            return false;
        }
        return true;
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.title_right_iv:
                    finish();
                    break;
                case R.id.register_smsBTN:
                    String mobile = phoneET.getText().toString();
                    Logger.i("mobile:"+mobile);
                    if(!TextUtils.isEmpty(phoneET.getText().toString())){
                        if(isMobileNo(mobile)){
                            if(isForgetPWD){
                                getForgetPWDSMS();
                            }else{
                                getREGSMS();
                        }
                        timeCountUtil = new TimeCountUtil(RegisterActivity.this, 60000, 1000, getSMS);
                        timeCountUtil.start();
                       }else {
                            toast("请输入正确手机号", 2000);
                        }
                    }else{
                            toast("请输入手机号", 2000);
                        }
                    break;
                case R.id.registerCPB:
                     if(!isForgetPWD){
                         doRegister();
                     }else{
                         doForgetPWD();
                     }
                    break;
                case R.id.protocol_link_tv:
                     startActivity(new Intent(RegisterActivity.this, ProtocolWebActivity.class));
                    break;
            }
        }
    };

    private void doRegister() {
        RegistrationRequest request = new RegistrationRequest();
        request.cellphone = phoneET.getText().toString();
        request.password = pwdET.getText().toString();
        request.verify_code = codeET.getText().toString();

        getHttpCenter().startHttpRequest(this, request, RegisterResult.class, new ResultListener<RegisterResult>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(RegisterResult mRegisterResult) {
                registerCPB.setProgress(100);
                Intent intent = new Intent(RegisterActivity.this, SelectCharacterActivity.class);
                intent.putExtra("register_result", mRegisterResult);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailed(int returnCode, String returnMsg) {

            }
        });
    }

    private void doForgetPWD() {
         FindPWDRequest  request = new FindPWDRequest();
         request.cellphone = phoneET.getText().toString();
         request.password = pwdET.getText().toString();
         request.verify_code = codeET.getText().toString();


         getHttpCenter().startHttpRequest(this, request, FindPWDResult.class, new ResultListener<FindPWDResult>() {
             @Override
             public void onStart() {

             }

             @Override
             public void onFinish() {

             }

             @Override
             public void onSuccess(FindPWDResult mResult) {
                 if(!TextUtils.isEmpty(mResult.getError())){
                     registerCPB.setProgress(100);
                 }else{
                     registerCPB.setProgress(0);
                     toast(mResult.getError(), 2000);
                 }
             }

             @Override
             public void onFailed(int returnCode, String returnMsg) {

             }
         });
    }

    private boolean isMobileNo(String mobiles) {
        Pattern  p =Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher  m = p.matcher(mobiles);
        System.out.println(m.matches() + "----");
        return m.matches();
    }

    private void getForgetPWDSMS() {
        ForgetPWDCodeRequest request = new ForgetPWDCodeRequest();
        Logger.i("request:" + request);
        request.cellphone = phoneET.getText().toString();

        getHttpCenter().startHttpRequest(this, request, ForgetPWDResult.class, new ResultListener<ForgetPWDResult>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ForgetPWDResult mResult) {
                Logger.i("mResult:");
                if(!TextUtils.isEmpty(mResult.getError())){
                    toast(mResult.getError(), 2000);
                    if(null != timeCountUtil){
                        timeCountUtil.cancel();
                    }
                    getSMS.setText("重新获取");
                    getSMS.setClickable(true);//重新获得点击
                    getSMS.setBackground(getResources().getDrawable(R.drawable.selector_btn_code_yellow));//还原背景色
                }
            }

            @Override
            public void onFailed(int returnCode, String returnMsg) {
                Logger.i("onFailed()");
            }
        });
    }

    private void getREGSMS() {
        SendREGCodeRequest  request = new SendREGCodeRequest();
        Logger.i("request:" + request);
        request.cellphone = phoneET.getText().toString();

        getHttpCenter().startHttpRequest(this, request, ForgetPWDResult.class, new ResultListener<ForgetPWDResult>() {
            @Override
            public void onStart() {
               Logger.i("onStart()");
            }

            @Override
            public void onFinish() {
                Logger.i("onFinish()");
            }

            @Override
            public void onSuccess(ForgetPWDResult mResult) {
                Logger.i("onSuccess()");
                if(!TextUtils.isEmpty(mResult.getError())){
                    toast(mResult.getError(), 2000);
                    if(null != timeCountUtil){
                        timeCountUtil.cancel();
                    }
                    getSMS.setText("重新获取");
                    getSMS.setClickable(true);//重新获得点击
                    getSMS.setBackground(getResources().getDrawable(R.drawable.selector_btn_code_yellow));//还原背景色
                }
            }

            @Override
            public void onFailed(int returnCode, String returnMsg) {
                Logger.i("onFailed()");
            }
        });
    }

    public class TimeCountUtil extends CountDownTimer{
        Activity mActivity;
        Button btn;

        // 在这个构造方法里需要传入三个参数，一个是Activity，一个是总的时间millisInFuture，一个是countDownInterval，然后就是你在哪个按钮上做这个是，就把这个按钮传过来就可以了
        public TimeCountUtil(RegisterActivity mActivity, long millisInFuture, long countDownInterval, Button btn) {
            super(millisInFuture, countDownInterval);
            this.mActivity = mActivity;
            this.btn = btn;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn.setClickable(false); //设置不能点击
            btn.setText("" + millisUntilFinished / 1000); //设置倒计时时间
            btn.setTextSize(15);

            //设置按钮为灰色，这时是不能点击的
            btn.setBackground(mActivity.getResources().getDrawable(R.drawable.selector_btn_valid_gray));
            String   text = btn.getText().toString();
            Spannable  spannable = new SpannableString(text);
            spannable.setSpan(new ForegroundColorSpan(Color.RED), 0, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); //讲倒计时时间显示为红色
        }

        @Override
        public void onFinish() {
            btn.setText("重新获取");
            btn.setClickable(true); //重新获得点击
            btn.setBackground(mActivity.getResources().getDrawable(R.drawable.selector_btn_code_yellow)); //还原背景色
        }
    }
}
